package com.wenhao.leetcode.easy;

/**
 * @author Wenhao Tong
 * @create 2021-07-12 15:51
 */
public class LeetCode67 {
    public static void main(String[] args) {
        LeetCode67 leetCode67 = new LeetCode67();
        String s = leetCode67.addBinary("1", "0");
        System.out.println(s);
    }

    /**
     * 可以用0将两个字符串变为一样长，这样写出来的代码比较简洁
     */
    public String addBinary(String a, String b) {
        char[] longer;
        char[] shorter;
        if (a.length() > b.length()) {
            longer = a.toCharArray();
            shorter = b.toCharArray();
        } else {
            shorter = a.toCharArray();
            longer = b.toCharArray();
        }
        int up = 0;
        int l = longer.length - 1;
        int s = shorter.length - 1;
        while (s > -1) {
            int temp = up + longer[l] + shorter[s--] - 2 * '0';
            longer[l--] =(char) ((temp % 2) + '0');
            up = temp / 2;
        }
        while (l > -1) {
            int temp = longer[l] + up - '0';
            longer[l] = (char) ((longer[l--] + up) % 2 + '0');
            up = temp / 2;
            if (up == 0) {
                return new String(longer);
            }
        }
        if (up == 0) {
            return new String(longer);
        }
        return 1 + new String(longer);
    }
}
